#!/bin/bash

set -e

# =============================================================================

readonly DOCKER_CONFIG_PATH="/etc/docker/daemon.json"
readonly DOCKER_DEFAULT_DATA_ROOT="/var/lib/docker"

# cloud-init/mount-nvme-instance-store
readonly INSTANCE_STORE="/mnt/ephemeral"

# =============================================================================

# Prefer NVMe instance store (if available) as Docker data dir
function get_docker_data_root {
  if [[ -d "$INSTANCE_STORE" ]]; then
    echo "$INSTANCE_STORE/docker"
  else
    echo "$DOCKER_DEFAULT_DATA_ROOT"
  fi
}

function prepare_docker_data_root {
  local readonly data_root=$(get_docker_data_root)
  if [[ "$data_root" != "$DOCKER_DEFAULT_DATA_ROOT" ]]; then
    >&2 echo -e "Symlink $DOCKER_DEFAULT_DATA_ROOT -> $data_root"
    mkdir -p "$data_root"
    ln -s "$data_root" "$DOCKER_DEFAULT_DATA_ROOT"
  fi
}

# https://docs.docker.com/config/daemon/systemd/
# https://docs.docker.com/engine/reference/commandline/dockerd/#daemon-configuration-file
function generate_docker_config {
  # Include nomad metadata from environment variables,
  # which can be converted to Loki labels.
  # https://www.nomadproject.io/docs/runtime/environment
  # https://docs.docker.com/config/containers/logging/json-file/#options
  cat > "$DOCKER_CONFIG_PATH" <<EOF
{
  "log-driver": "json-file",
  "log-opts": {
    "env": "NOMAD_NAMESPACE,NOMAD_JOB_NAME,NOMAD_GROUP_NAME,NOMAD_TASK_NAME,NOMAD_ALLOC_ID",
    "max-size": "256m",
    "max-file": "2"
  }
}
EOF
}

function start_docker {
  systemctl enable containerd.service
  systemctl enable docker.service
  systemctl start containerd.service
  systemctl start docker.service
}

function run {
  prepare_docker_data_root
  generate_docker_config
  start_docker
}

run "$@"
